package com.xisoft.devise.controller;

import com.xisoft.common.aspect.AppMonitorRuning;
import com.xisoft.common.io.FileUtilbc;
import com.xisoft.common.io.StreamUtil;
import com.xisoft.common.result.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * *
 * Created with Description:
 *
 * @version 1.0 <br>
 * @packagename: com.xisoft.devise.controller<br>
 * @author: LiBencheng <br>
 * @computer: licheng <br>
 * @date: Created on 2022/9/26 14:02 <br>
 */
@RestController
@RequestMapping ("file")
public class FileController
{
    @RequestMapping (value = "/upload", method = RequestMethod.POST)
    @AppMonitorRuning (method = "FileController.upload", funEffect = "上传方法")
    public void testUploadFile(HttpServletRequest req, MultipartHttpServletRequest multiReq) throws IOException
    {
        MultipartFile multipartFile = multiReq.getFileMap().get("file");
        String fileName = "D:\\OneDrive\\" + multipartFile.getResource().getFilename();
        FileOutputStream fos = new FileOutputStream(new File(fileName));
        FileInputStream fs = (FileInputStream) multipartFile.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fs.read(buffer)) != -1)
        { fos.write(buffer, 0, len); }

        FileUtilbc.close(fos, fs);
    }

    @RequestMapping (value = "/download", method = RequestMethod.GET)
    @AppMonitorRuning (method = "FileController.download", funEffect = "下載方法")
    public void download(HttpServletResponse resp) throws IOException
    {
        ZipOutputStream zos = null;
        InputStream input = null;
        try
        {
            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment;filename=xisoft.zip");
            zos = new ZipOutputStream(resp.getOutputStream());
            List< File > files = FileUtilbc.listFile("D:\\OneDrive\\sqlScript");
            // 打包压缩
            for (File file : files)
            {
                // File file = new File(filePath);
                // 一个文件对应一个ZipEntry
                ZipEntry zipEntry = new ZipEntry(file.getName());
                input = new FileInputStream(file);
                zos.putNextEntry(zipEntry);
                IOUtils.copy(input, zos);
            }
            resp.flushBuffer();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            FileUtilbc.close(zos, input);
        }

    }


    @RequestMapping (value = "/downPrintBatchFile")
    @AppMonitorRuning (method = "FileController.send", funEffect = "下载压缩文件！")
    public Result downPrintBatchFile(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String patch = "D:\\OneDrive\\sqlScript";
        BufferedInputStream bis = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        List< File > sourceFiles = FileUtilbc.listFile(patch);
        byte[] buffer = new byte[4096];

        for (int i = 0; i < sourceFiles.size(); ++i)
        {
            String fileName = ((File) sourceFiles.get(i)).getPath();
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOutputStream.putNextEntry(zipEntry);
            bis = new BufferedInputStream(new FileInputStream((File) sourceFiles.get(i)), 4096);
            boolean var9 = false;
            int read = 0;
            // while ((read = bis.read()) != -1)
            // { zipOutputStream.write(read); }
            while ((read = bis.read(buffer)) != -1)
            { zipOutputStream.write(buffer, 0, read); }
        }
        new File("d:/text.zip").createNewFile();
        StreamUtil.writeByteArrayToFile(new File("d:/text.zip"), buffer);
        // zip(zipOutputStream, new File("d:/text.zip"), "");
        // 远程部署需要下载到客户端到本地
        byte[] data = StreamUtil.readFileToByteArray(new File("d:/text.zip"));
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"xisoft-code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        // response.setContentType("application/octet-stream; charset=UTF-8");
        response.setContentType("application/x-download");
        response.getOutputStream().write(data);
        FileUtilbc.close(response.getOutputStream());

        return Result.ok("");
    }


    private void zip(ZipOutputStream out, File f, String base) throws Exception
    {
        if (f.isDirectory())
        {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++)
            {
                zip(out, fl[i], base + fl[i].getName());
            }
        }
        else
        {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b;
            while ((b = in.read()) != -1)
            { out.write(b); }
            in.close();
        }
    }
}
